package com.xbongbong.pro.statistics.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.bi.SubsidiaryEnum;
import com.xbongbong.paas.enums.bi.XbbTableRefEnum;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsInitDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsInitVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.service.toolbox.statistic.help.TeamHelp;
import com.xbongbong.pro.statistics.service.CkPaasFormDataService;
import com.xbongbong.saas.domain.entity.WorkOrderFlowUserEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.help.InitDataHelp;
import com.xbongbong.saas.model.AssembleProductModel;
import com.xbongbong.saas.model.BomProductModel;
import com.xbongbong.saas.model.ContractPerformanceModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.InventoryProductModel;
import com.xbongbong.saas.model.OpportunityProductModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductionOrderProductModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.QuotationProductModel;
import com.xbongbong.saas.model.ReturnedPurchaseProductModel;
import com.xbongbong.saas.model.SupplierProductModel;
import com.xbongbong.saas.model.TransferProductModel;
import com.xbongbong.saas.model.WorkOrderFlowUserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 自定义统计的返回值
 * @author 梁鲁江
 * @version v1.0
 * @date 2019/4/16 16:08
 * @since v1.0
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/ck/script")
public class CkJobController {
    @Resource
    private WorkOrderFlowUserModel workOrderFlowUserModel;
    @Resource
    private CkPaasFormDataService ckPaasFormDataService;
    @Resource
    private InitDataHelp initDataHelp;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private TeamHelp teamHelp;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private OpportunityProductModel opportunityProductModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private ProductionOrderProductModel productionOrderProductModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private ReturnedPurchaseProductModel returnedPurchaseProductModel;
    @Resource
    private SupplierProductModel supplierProductModel;
    @Resource
    private ContractPerformanceModel contractPerformanceModel;
    @Resource
    private AssembleProductModel assembleProductModel;
    @Resource
    private InventoryProductModel inventoryProductModel;
    @Resource
    private TransferProductModel transferProductModel;
    @Resource
    private QuotationProductModel quotationProductModel;
    @Resource
    private BomProductModel bomProductModel;

    private static final Logger LOG = LoggerFactory.getLogger(CkJobController.class);
    
    @RequestMapping(value = "/transWorkUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String transWorkUser(@RequestBody PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) {
        XbbResponse<PaasFormDataEsInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
                if(byCorpid != null && Objects.equals(0,byCorpid)){
                    paasFormDataEsInitDTO.setCorpid(null);
                }
                Integer pageSize = paasFormDataEsInitDTO.getPageSize();
                if (pageSize == null) {
                    paasFormDataEsInitDTO.setPageSize(SizeConstant.PAGE_SIZE);
                }
                Map<String, Object> params = BeanUtil.convertBean2Map(paasFormDataEsInitDTO, true,true);
                params.put("orderByStr", "id");
                boolean flag = true;
                while (flag) {
                    List<WorkOrderFlowUserEntity> list = workOrderFlowUserModel.findEntitys(params);
                    if (list == null || list.isEmpty()) {
                        flag = false;
                    } else {
                        //大于上次最大的id
                        WorkOrderFlowUserEntity o = list.get(list.size() - 1);
                        params.put("idGte", o.getId());
                        ckPaasFormDataService.insertBatch(list,2302);
                        LOG.info("businessType:" + paasFormDataEsInitDTO.getBusinessType() + "    max id :" + o.getId());
                    }
                }
                PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
                response = new XbbResponse<>(paasFormDataEsInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
    @RequestMapping(value = "/countNum", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String countNum(@RequestBody PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) {
        LOG.info("-------------------------------------------------------------");
        XbbResponse<PaasFormDataEsInitVO> response = null;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                for (XbbTableRefEnum value : XbbTableRefEnum.values()) {
                    if(Objects.equals(XbbTableRefEnum.UNKNOWN.getCode(),value.getCode())){
                        continue;
                    }
                    Integer ckConut = ckPaasFormDataService.countBySql("select COUNT(*) FROM " + value.getTableName() +
                            "  final");
                    Integer mySqlConut = ckPaasFormDataService.countBySqlMySql("select COUNT(*) FROM " + value.getTableName());
                    if(Objects.equals(ckConut,mySqlConut)){
                        LOG.info("=====equal====="+ value.getCode());
                    }else {
                        LOG.info("=====noeequal====="+ value.getCode()+ "======ck====="+ ckConut + "===mysql=="+ mySqlConut);
                    }

                }
                if(true){
                    return "x";
                }
                PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
                response = new XbbResponse<>(paasFormDataEsInitVO);
            }catch (Exception e){
                LOG.info("exception===",e);
            }finally {
                LOG.info("-------------------------------------------------");
                LOG.info("--------------------执行结束---------------------");
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
    @RequestMapping(value = "/transInitData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String transInitData(@RequestBody PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) {
        LOG.info("-------------------------------------------------------------");
        LOG.info("-------------------------------------------------------------");
        LOG.info("------------------------开始数据同步---------------------------");
        XbbResponse<PaasFormDataEsInitVO> response = null;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(CollectionsUtil.isNotEmpty(paasFormDataEsInitDTO.getBusinessTypeList())){
                    for (Integer integer : paasFormDataEsInitDTO.getBusinessTypeList()) {
                        paasFormDataEsInitDTO.setBusinessType(integer);
                        initData(paasFormDataEsInitDTO);
                        paasFormDataEsInitDTO.setIdGte(null);
                    }
                }else {
                    initData(paasFormDataEsInitDTO);
                }
                if(true){
                    return "x";
                }
                PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
                response = new XbbResponse<>(paasFormDataEsInitVO);
            } catch (XbbException e) {
                LOG.info("XbbException",e);
                response = new XbbResponse<>(e);
            }catch (Exception e){
                LOG.info("exception",e);
            }finally {
                LOG.info("-------------------------------------------------");
                LOG.info("--------------------执行结束---------------------");
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    private String initData(PaasFormDataEsInitDTO paasFormDataEsInitDTO) throws XbbException {
        Integer businessType = paasFormDataEsInitDTO.getBusinessType();
        XbbTableRefEnum xbbTableRefEnum = XbbTableRefEnum.getByCode(businessType);
        String tableName = xbbTableRefEnum.getTableName();
        if (StringUtil.isEmpty(tableName)) {
            return "未查询到对应的表，无法插入数据";
        }
        LOG.info("------------------记录1-------------------------------");
        List<String> columns = ckPaasFormDataService.getColumnNameByTableName(tableName);
        if(CollectionsUtil.isEmpty(columns)){
            return "数据库没有该表，无法插入数据";
        }
        Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
        if(byCorpid != null && Objects.equals(0,byCorpid)){
            paasFormDataEsInitDTO.setCorpid(null);
        }
        Integer pageSize = paasFormDataEsInitDTO.getPageSize();
        if (pageSize == null) {
            paasFormDataEsInitDTO.setPageSize(SizeConstant.PAGE_SIZE);
        }
        Map<String, Object> params = BeanUtil.convertBean2Map(paasFormDataEsInitDTO, true,true);
        params.put("orderByStr", "id");
        boolean flag = true;
        int totalSize = 0;
        while (flag) {
            LOG.info("------------------记录2-------------------------------");
            List list = null;
            if(Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.MASTER.getCode())){
                Integer saasMark = SaasMarkEnum.SAAS.getCode();
                if(Objects.equals(businessType, XbbRefTypeEnum.PAAS.getCode())){
                    saasMark = SaasMarkEnum.PAAS.getCode();
                }
                list = initDataHelp.getList(businessType, saasMark, params, 1, null);
            }else if(Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.USER.getCode())){
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                if (Objects.equals(businessType, IndexTypeEnum.IDX_STATICS_MARKET_DATA.getCode())) {
                    xbbRefTypeEnum = XbbRefTypeEnum.MARKET_ACTIVITY_STATIC;
                }
                list = teamHelp.getList(xbbRefTypeEnum, params, list);
            }else if(Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.SUB_DATA.getCode())){
                Integer saasMark = SaasMarkEnum.SAAS.getCode();
                IndexTypeEnum indexTypeEnum = EsUtil.getIndexTypeEnum(saasMark, businessType);
                if(Objects.equals(businessType,XbbRefTypeEnum.PAAS_SUBFORM.getCode())){
                    indexTypeEnum = IndexTypeEnum.IDX_SUB_FORM_DATA;
                }
                list = paasFormSubDataModel.getSubDataList(params, indexTypeEnum);
            }else if(Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.RELATED_PRODUCT.getCode()) || Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.PERFORMANCE.getCode())){
                switch (xbbTableRefEnum){
                    case CONTRACT_PRODUCT:
                        list = contractProductModel.findEntitys(params);
                        break;
                    case SALES_OPPORTUNITY_PRODUCT:
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = opportunityProductModel.findEntitys(params);
                        break;
                    case QUOTATION_PRODUCT :
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = quotationProductModel.findEntitys(params);
                        break;
                    case SUPPLIER_PRODUCT:
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = supplierProductModel.findEntitys(params);
                        break;
                    case PURCHASE_PRODUCT:
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = purchaseProductModel.findEntitys(params);
                        break;
                    case RETURNEDPURCHASE_PRODUCT:
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = returnedPurchaseProductModel.findEntitys(params);
                        break;
                    case BOM_BILL_PRODUCT:
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = bomProductModel.findEntitys(params);
                        break;
                    case PRODUCTION_ORDER_PRODUCT:
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = productionOrderProductModel.findEntitys(params);
                        break;
                    case ASSEMBLE_PRODUCT:
                        list = assembleProductModel.findEntitys(params);
                        break;
                    case INVENTORY_PRODUCT:
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = inventoryProductModel.findEntitys(params);
                        break;
                    case TRANSFER_PRODUCT:
                        //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                        list = transferProductModel.findEntitys(params);
                        break;
                    case INSTOCK_PRODUCT:
                        list = instockProductModel.findEntitys(params);
                        break;
                    case OUTSTOCK_PRODUCT:
                        list = outstockProductModel.findEntitys(params);
                        break;
                    case CONTRACT_PERFORMANCE:
                        list = contractPerformanceModel.findEntitys(params);
                        break;
                    default:
                        break;
                }
            }else {
                LOG.error("=========================没有"+ businessType);
            }
            if (list == null || list.isEmpty()) {
                LOG.info("------------------记录4-------------------------------");
                flag = false;
            } else {
                //大于上次最大的id
                Object o = list.get(list.size() - 1);
                Long id = null;
                if(Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.MASTER.getCode())){
                    PaasFormDataEntity paasFormDataEntity = (PaasFormDataEntity) o;
                    id = paasFormDataEntity.getId();
                }else if(Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.USER.getCode()) || Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.SUB_DATA.getCode()) || Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.RELATED_PRODUCT.getCode()) || Objects.equals(xbbTableRefEnum.getSubsidiary(), SubsidiaryEnum.PERFORMANCE.getCode())){
                    JSONObject json = JSONObject.parseObject(JSON.toJSONString(o));
                    id = json.getLong("id");
                }

                params.put("idGte", id);
                if (CollectionsUtil.isNotEmpty(list)){
                    int i = list.size() / SizeConstant.PAGE_SIZE;
                    int i1 = list.size() % SizeConstant.PAGE_SIZE;
                    if (i1 != 0){
                        i++;
                    }
                    int startIndex ;
                    int endIndex ;
                    for (int j = 0; j < i; j++) {
                        startIndex = j * SizeConstant.PAGE_SIZE;
                        endIndex = startIndex + SizeConstant.PAGE_SIZE;
                        List list1 = list.subList(Math.min(startIndex, list.size()), Math.min(endIndex, list.size()));
                        totalSize += list1.size();
                        ckPaasFormDataService.insertBatch(list1,columns,tableName);
                        LOG.info("businessType:" + businessType + " 已插入 :" + totalSize + "条！");
                    }
                }
                LOG.info("businessType:" + businessType + " max id :" + id);
            }
        }
        LOG.info("-----------------------Sync complete----------------------");
        return null;
    }

    @RequestMapping(value = "/transSubData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String transSubData(@RequestBody PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) {
        XbbResponse<PaasFormDataEsInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                Integer byCorpid = paasFormDataEsInitDTO.getByCorpid();
                if(byCorpid != null && Objects.equals(0,byCorpid)){
                    paasFormDataEsInitDTO.setCorpid(null);
                }
                Integer pageSize = paasFormDataEsInitDTO.getPageSize();
                if (pageSize == null) {
                    paasFormDataEsInitDTO.setPageSize(SizeConstant.PAGE_SIZE);
                }
                Map<String, Object> params = BeanUtil.convertBean2Map(paasFormDataEsInitDTO, true,true);
                params.put("orderByStr", "id");
                boolean flag = true;
                IndexTypeEnum indexTypeEnum = EsHelper.getIndexTypeEnum(paasFormDataEsInitDTO.getSaasMark(),paasFormDataEsInitDTO.getBusinessType());
                while (flag) {
                    List<? extends PaasFormSubDataEntity> list = paasFormSubDataModel.getSubDataList(params, indexTypeEnum);
                    if (list == null || list.isEmpty()) {
                        flag = false;
                    } else {
                        //大于上次最大的id
                        params.put("idGte", list.get(list.size() - 1).getId());
                        ckPaasFormDataService.insertBatch(list,paasFormDataEsInitDTO.getBusinessType());
                        LOG.info("businessType:" + paasFormDataEsInitDTO.getBusinessType() + " max id :" + list.get(list.size() - 1).getId());
                    }
                }
                PaasFormDataEsInitVO paasFormDataEsInitVO = new PaasFormDataEsInitVO();
                response = new XbbResponse<>(paasFormDataEsInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }



}
